import {delCartAPI, findNewCartListAPI, insertCartAPI, updateCartGoods} from "@/apis/cart.js";
import {useUserStore} from "@/stores/userStore.js";
import {ElMessage} from "element-plus";

export const useCartStore = defineStore(
    'cart',
    () => {
        const cartList = ref([]);
        const userStore = useUserStore();
        const isLogin = computed(() => userStore.userInfo.token);

        // 获取登录后最新购物车列表action
        const updateLoginCartList = async () => {
            const res = await findNewCartListAPI()
            console.log("findNew",res.data)
            cartList.value = res.data
        }

        const addCart = async (goods)=> {
            if (isLogin.value) {
                //登录之后加入购物车逻辑
                const res = await insertCartAPI(goods)
                if(res.data){
                    ElMessage.success("添加成功")
                }else{
                    ElMessage.error("添加失败")
                }
                await updateLoginCartList()
            } else {
                const findItem = cartList.value.find(item => goods.skuId === item.skuId);
                if (findItem) {
                    findItem.count += goods.count;
                } else {
                    cartList.value.push(goods)
                }
            }
        }
        const delCart = async (skuId) => {
            if(isLogin.value) {
                //登录之后删除购物车逻辑
                console.log([skuId])
                const res = await delCartAPI([skuId])
                console.log("res",res)
                if(res.data){
                    ElMessage.success("删除成功")
                }else{
                    ElMessage.error("删除失败")
                }
                await updateLoginCartList()
            }else {
                // 思路：
                // 1. 找到要删除项的下标值 - splice
                // 2. 使用splice删除找到的项，原数组改变
                console.log("del", cartList.value)
                const idx = cartList.value.findIndex((item) => skuId === item.skuId)
                cartList.value.splice(idx, 1)
            }
        }
        // 计算属性
        // 1. 总的数量 所有项的count之和
        const allCount = computed(() => cartList.value.reduce((a, c) => a + c.quantity, 0))
        // 2. 总价 所有项的count*price之和
        const allPrice = computed(() => cartList.value.reduce((a, c) => a + c.quantity * c.unitPrice, 0))

        //3、是否全选
        const changeBox = (selected) => {
            cartList.value.forEach(item => item.selected = selected)
        }

        //4、已选择的数量、价格
        const selectCount = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.quantity, 0))
        const selectAllPrice = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.quantity * c.unitPrice, 0))
        //5、是否全选计算属性
        const isAll = computed(() => cartList.value.every((item) => item.selected))
        //6、修改购物车项
        //修改购物项
        const updateCartItem = async (goods) => {
            const {skuId,quantity,selected} = goods
            if (isLogin.value) {
                const res = await updateCartGoods({skuId,quantity,selected})
                console.log("res",res)
                if(res.data!=null&&!res.data){
                    ElMessage.error("更新失败")
                }
                await updateLoginCartList()
            }
        }
        //7、用户退出后清空
        const clearCart = () => {
            cartList.value = []
        }
        return {
            //属性
            cartList,
            allCount,
            allPrice,
            isAll,
            selectCount,
            selectAllPrice,
            //方法
            addCart,
            delCart,
            changeBox,
            updateLoginCartList,
            clearCart,
            updateCartItem
        }
    },
    {
        persist: true
    }
)